'''
Created on Apr 16, 2012

@author: ke
'''
from google.appengine.ext import webapp
#from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
#from google.appengine.ext.db import djangoforms
from google.appengine.api import users
import urllib2
import numpy as np
import csv
from history import *
import datetime
import tools.AlchemyAPI as nlp
from bs4 import BeautifulSoup
from twitter import Twitter
import tools.twokenize as twokenize
from tools.emoticons import analyze_tweet
from tools.sentiment import *
from tools import gp


class GeneticCompute(webapp.RequestHandler):
    
    def get_input_data(self, var1, var2, target):
        try:
            x = var1.replace(' ','').split(';')
            for i in range(len(x)):
                x[i] = float(x[i])
            y = var2.replace(' ','').split(';')
            for i in range(len(y)):
                y[i] = float(y[i])
            t = target.replace(' ','').split(';')
            for i in range(len(t)):
                t[i] = float(t[i])
            
            #print [x, y, t]
            if (len(x)==len(y)) and (len(y)==len(t)):
                return (True, [x, y, t])
            else:
                return (False, 0)
        except:
            return (False, 0)
        return (False, 0)
    
    def get(self):
        html =template.render('templates/genetic_form.html', {})
        self.response.out.write(html)
        
        #rf=gp.getrankfunction(gp.buildhiddenset())
        #gp.evolve(2, 100, rf, mutationrate = 0.2, breedingrate = 0.1, pexp = 0.7, pnew = 0.1, precision=0.05)
    
    def post(self):
        v1 = self.request.get('var1')
        v2 = self.request.get('var2')
        t = self.request.get('target')
        
        (flag, input) = self.get_input_data(var1=v1, var2=v2, target=t)
        
        if flag:
            rf=gp.getrankfunction(input)
            gp.evolve(2, 100, rf, mutationrate = 0.2, breedingrate = 0.1, pexp = 0.7, pnew = 0.1, precision=0.05)
        else:
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write('Invalid inputs')
            
        
        
        
        new_geneticHistory = GeneticHistory()
        new_geneticHistory.var1 = v1
        new_geneticHistory.var2 = v2
        new_geneticHistory.target = t
        new_geneticHistory.user = users.get_current_user()
        new_geneticHistory.query_date = datetime.date.today()
        
        new_geneticHistory.put()